﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using QH_MSS_WPF_Core.UserControls;
using System.Text.RegularExpressions;

namespace QH_MSS_WPF_Core.Extensions
{
    public partial class TouchTextBox
    {
        private Control hostControl;

        //OnClick方法调用时，通过Window.ShowDialog方法，打开KeyboardControl
        public void OnClick(object sender, TouchEventArgs e)
        {
            if (sender is TextBox textBox)
            {
                hostControl = textBox;
                //计算KeyboardControl的位置，弹出KeyboardControl Regex.Replace(str, @"[^\d.\d]", "");
                var text = Show(Regex.Replace(textBox.Text, @"[^\d.\d]", ""), textBox);
                //KeyboardControl关闭后，获取其文本值，赋值给TextBox
                if (!string.IsNullOrEmpty(text))
                {
                    textBox.Text = text;
                }
                else
                {
                    textBox.Text = string.Empty;
                }
            }
        }

        private string Show(string initValue, object sender = null)
        {
            var keyboard = new NumericKeyBoardUserControl(initValue);
            SetPosition(keyboard);
            bool result = keyboard.ShowDialog().Value;
            return keyboard.TextStr;
        }

        private void SetPosition(Window window)
        {
            Point point = hostControl.PointFromScreen(new Point(0.0, 0.0));
            double width = SystemParameters.WorkArea.Width;
            double height = SystemParameters.WorkArea.Height;
            if (-point.Y + hostControl.ActualHeight + 5.0 + window.Height < height)
            {
                window.Top = -point.Y + hostControl.ActualHeight + 5.0;
            }
            else
            {
                window.Top = -point.Y - window.Height - 5.0;
            }
            if (-point.X + window.Width < width)
            {
                window.Left = -point.X;
            }
            else
            {
                window.Left = -point.X - (window.Width - hostControl.ActualWidth);
            }
        }
    }
}
